import React, { Component } from 'react';
import {
  StyleSheet, View, DeviceEventEmitter, Text, TouchableOpacity,
} from 'react-native';
import produce from 'immer';
import { Accordion } from 'native-base';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import Theme from '../../../../native-base-theme/variables/commonColor';
import SelectPart from '../../../../components/selectIncidentpart';
import * as techDocService from '../../../../services/techDoc';
import { UtilToast } from '../../../../utils/util-method';
import { FormButtonRadio, SearchBarHeaderImage } from '../../../../components';
import ZlstIcon from '../../../../components/zlst-icons';

class SparePartsInventoryInfo extends Component {
  static navigationOptions = {
    title: '备件库存',
    headerStyle: { backgroundColor: Theme.toolbarDefaultBg, borderBottomWidth: 0, elevation: 0 },
    headerTintColor: '#FFFFFF',
    headerTitleStyle: {
      fontWeight: 'bold',
      fontSize: 20,
      flex: 1,
      textAlign: 'center',
    },
    headerBackImage: (
      <ZlstIcon
        name="fanhui"
        size={24}
        color="white"
      />
    ),
    headerRight: <View />,
  }

  constructor(props) {
    super(props);
    this.state = {
      datas: [{ description: 'Inter酷睿I7', lubeType: '21', lubeModel: '11', datas: [{ name: '合金部配送站', num: '2' }, { name: '检修班配送站', num: '3' }] }],
      showSelectIncidentPart: false,
      location: '',
      category: [],
    };
  }

  componentDidMount() {
    // this.getDatas();
    const { category } = this.props.navigation.state.params;
    this.setState({ category });
  }

  // 获取技术性能信息
  getDatas = async () => {
    try {
      DeviceEventEmitter.emit('showLoading', true);
      const { datas } = this.props.navigation.state.params;
      if (datas && datas.objType) {
        // const data = await techDocService.tdLubrication({ objType: datas.objType });
        const data = await techDocService.tdLubrication({ objType: 'RX_KYZGSZ' });
        DeviceEventEmitter.emit('showLoading', false);
        if (data && data.length > 0) {
          this.setState(produce(draft => {
            draft.datas = data;
          }));
        } else {
          UtilToast('该设备暂无润滑标准信息', 'danger');
        }
      } else {
        DeviceEventEmitter.emit('showLoading', false);
        UtilToast('没有设备信息', 'danger');
      }
    } catch (e) {
      console.log(e);
      DeviceEventEmitter.emit('showLoading', false);
    }
  }

  category = (v) => {
    const category = this.state.category.map(it => ({
      ...it,
      checked: it.name === v.name,
    }));

    this.setState(produce(draft => {
      draft.category = category;
    }));
  }

  _hideSelect = () => {
    this.setState({
      showSelectIncidentPart: false,
    });
  }

  _selectLocation = () => {
    const { datas } = this.props.navigation.state.params;
    if (datas && datas.equipmentId && datas.objType) {
      this.setState({
        showSelectIncidentPart: true,
      });
    } else {
      DeviceEventEmitter.emit('showLoading', false);
      UtilToast('没有设备信息', 'danger');
    }
  }

  _onSearch = async () => {
    this.props.navigation.navigate({
      routeName: 'SearchSpareParts',
    });
  }

  _finishSelectPart = async (selectedList) => { // 故障位置选择结束
    if (selectedList && selectedList.length) {
      const material = selectedList[selectedList.length - 1];
      this.setState({ location: material.description });
      // this.getDatas(material.splitItemId);
      this.getDatas();
    }
  }

  // 跳转到库存详情页面
  toDetail = (sparePart, repertory) => {
    // const { datas } = this.props.navigation.state.params;
    this.props.navigation.navigate({
      routeName: 'SparePartsInventoryDetail',
      params: {
        sparePart,
        repertory,
      },
    });
  }

  _renderHeader(item, expanded) {
    return (
      <View style={{
        flexDirection: 'row',
        padding: 8,
        marginTop: 8,
        marginLeft: 8,
        marginRight: 8,
        justifyContent: 'space-between',
        borderRadius: 4,
        alignItems: 'center',
        backgroundColor: 'rgba(255,255,255,0.2)',
      }}
      >
        <View style={{ flex: 1, flexDirection: 'row' }}>
          <View style={{ flex: 5, justifyContent: 'center' }}>
            <Text style={{ color: 'white' }}>{item.description}</Text>
          </View>
          <View style={{ flex: 1, justifyContent: 'flex-end' }}>
            <Text style={{ color: 'white' }}>({item.lubeType} 块)</Text>
          </View>
        </View>
        {expanded
          ? <Icon style={{ fontSize: 24, color: 'white' }} name="chevron-up" />
          : <Icon style={{ fontSize: 24, color: 'white' }} name="chevron-down" />}
      </View>
    );
  }

  _renderContent(item, toDetail) {
    return (
      <View style={{ backgroundColor: Theme.myPrimary, marginLeft: 8, marginRight: 8 }}>
        {
          item.datas.map((data, index) => (
            <TouchableOpacity onPress={() => toDetail(item.description, data.name)} key={index}>
              <Text style={{ padding: 8, color: 'white' }}>
                {data.name}：{data.num} 块
              </Text>
            </TouchableOpacity>
          ))
        }
      </View>
    );
  }

  render() {
    const { datas } = this.props.navigation.state.params;
    return (
      <View style={styles.tabContent}>
        {this.state.showSelectIncidentPart && (
          <SelectPart
            show={this.state.showSelectIncidentPart}
            hide={this._hideSelect}
            equTypeId={datas.objType}
            equipmentId={datas.equipmentId}
            finish={this._finishSelectPart}
          />
        )}
        <SearchBarHeaderImage placeholder="备件搜索" search={this._onSearch} />
        <FormButtonRadio datas={this.state.category} _click={this.category} />
        <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 8 }}>
          <Text style={{ color: 'white', fontSize: 15 }}>选择位置</Text>
          <Text style={styles._button} onPress={() => this._selectLocation()}>选择</Text>
        </View>
        <View>
          <Text style={{ color: 'white', paddingTop: 8, paddingBottom: 8, paddingLeft: 16, fontSize: 15 }}>{this.state.location}</Text>
        </View>
        {this.state.datas.length > 0 && (
          <View>
            <Text style={{ color: 'white', paddingTop: 8, paddingBottom: 8, paddingLeft: 8, fontSize: 15 }}>备件库存</Text>
          </View>
        )}
        {this.state.datas.length > 0 && (
          <Accordion
            style={{ borderWidth: 0 }}
            dataArray={this.state.datas}
            renderHeader={this._renderHeader}
            renderContent={(item) => this._renderContent(item, this.toDetail)}
          />
        )}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  tabContent: {
    backgroundColor: Theme.myPrimary,
    width: '100%',
    height: '100%',
    padding: 8,
  },
  title: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#ffffff',
  },
  descriptionContainer: {
    flexDirection: 'row',
    paddingRight: 50,
  },
  textDescription: {
    color: '#ffffff',
  },
  _button: {
    width: 48,
    borderRadius: 2,
    textAlignVertical: 'center',
    padding: 4,
    color: 'white',
    textAlign: 'center',
    borderWidth: 1,
    borderStyle: 'solid',
    borderColor: 'white',
  },
});

export default SparePartsInventoryInfo;
